#!/usr/bin/env coffee

try
  await import('@rmw/console/global')

import './meta'
import Nkn from './nkn/init'
import * as CMD from '../src/const/cmd'
import SEED from './const/seed'
import {Meta} from './db/mdbx'
import Data from './data'
import dgram from 'dgram'
import Udp from './udp'

next = (msg)->
  if 0 == msg.length
    return

  cmd = msg[0]

  cmd_time = cmd == CMD.TIME
  if cmd_time or cmd == CMD.TIME_SIZE_HASH
    meta = await Meta.get msg[1..]
    if meta
      if cmd_time
        yield meta[...8]
      else
        yield meta
    return

  if 0
    yield

  return

  #if cmd == CMD.DATA
  #  # payload 需要切片一下，不然.buffer不等于payload
  #  view = new DataView(payload[1..].buffer)
  #  return Data(
  #    payload[1..32]
  #    view.getBigUint64(32, true)
  #  )



  #return


Udp().then (udp)=>
  udp.on 'message', (payload, {address,family,port,size})=>
    console.log payload
    for await i from next(payload)
      console.log "reply ",i
      udp.send(
        i
        port
        address
      )



Nkn(SEED.toString 'hex').then (nkn)=>
  nkn.onMessage ({src,payload})=>
    for await i from next(payload)
      nkn.send src, i, noReply:true


